import os
import random
import platform
import argparse

'''
RandomVid.py

Randomly opens a video from a set directory in mpv and then clears the terminal once mpv exits.
'''

videoFormats = ('.webm', '.mp4', '.mkv', '.flv', '.vob', '.ogv', '.gifv', '.avi', '.mov',
                '.wmv', '.m4p', '.m4v', '.mpg', '.mp2', '.mpeg', '.mpv', '.m2v', '.3pg')

# default arguments are to set volume half way, not resume and middle of screen video at half resolution
# see https://mpv.io/manual/master/#options for all options
mpvArgs = '--volume 50 --resume-playback no --geometry 50%x50%'

# pass an argument to load from a pool or none to enter a directory manually
# add/remove parser.add_argument lines in conjunction with the block below
parser = argparse.ArgumentParser()

# set custom directories here
parser.add_argument('-mm', '--memories', help='Videos from the memories directory', action='store_true')
parser.add_argument('-hv', '--homevideos', help='Home videos directory', action='store_true')
# end custom directories (don't forget to add them to the if statement below)

parser.add_argument('-o', '--ontop', help='Enforce topmost', action='store_true')
args = parser.parse_args()

# elif so mpv won't get a bunch of videos at once if multiple entries are used as args
if args.memories:
  os.chdir(r'e:\exampledir\memories')
elif args.homevideos:
  os.chdir(r'/home/example/Videos/homevideos')
else:
    # no argument supplied; ask for directory
    userDir = input('Where to?: ')
    os.chdir(userDir)


# set topmost/ontop
if args.ontop:
    mpvArgs = '{0} --ontop'.format(mpvArgs)

#where we're gonna store a list of all our files
total = list()

#lets iterate over all the directories & files
print('Walking through: {0}'.format(os.getcwd()))

for root, dirs, files in os.walk(".", topdown = False):
  for name in files:

  # lets make sure it's a video we're on
    if name.endswith(videoFormats):
      total.append(os.path.join(root, name))

# lets see how many items we have...
maxRange = len(total)
print('Total files {0}'.format(maxRange))

# lets choose 1 at random
print('Rolling dice...')
randomlySelected = random.randrange(0, maxRange)
print('Selected: {0}'.format(total[randomlySelected]))
print('Passing to mpv...')

# display a quick cheatsheet in the terminal for mpv
print('\n\tMPV CHEATSHEET\n\t* 9/0 - vol down/up\n\t* left/right - scroll forward/back 5 seconds\
     \n\t* up/down - scroll forward/back 60 seconds\n\t* space - pause\n\t* f - fullscreen\n\t* q - quit\n')

# execute mpv with the file & args
os.system('mpv "{file}" {mpvArgs}'.format(file=total[randomlySelected], mpvArgs=mpvArgs))

# clear the screen once mpv exits
if platform.system() == 'Windows':
  os.system('cls')
else:
  os.system('clear') # Darwin & Linux should accept 'clear'
